package com.zbcn.socket.self;

/**
 * @Description:
 * @Auther: zbcn8
 * @Date: 2019/4/18 18:48
 */
public class VoteMsg {
    /**
     * true 表示该消息是查询请求，false 表示该消息是投票请求；
     */
    private boolean isInquiry;
    /**
     * true 表示该消息是服务器发送的相应消息，false 表示该消息为客户端发送的请求消息；
     */
    private boolean isResponse;
    /**
     * 指示了候选人的 ID
     */
    private int candidateID;   // in [0,1000]
    /**
     * 指示出所查询的候选人获得的总选票数
     */
    private long voteCount;    // nonzero only in response

    public static final int MAX_CANDIDATE_ID = 1000;


    public VoteMsg(boolean isInquiry, boolean isResponse, int candidateID, long voteCount) {
        // check invariants
        if (voteCount != 0 && !isResponse) {
            throw new IllegalArgumentException("Request vote count must be zero");
        }
        if (candidateID < 0 || candidateID > MAX_CANDIDATE_ID) {
            throw new IllegalArgumentException("Bad Candidate ID: " + candidateID);
        }
        if (voteCount < 0) {
            throw new IllegalArgumentException("Total must be >= zero");
        }
        this.isInquiry = isInquiry;
        this.isResponse = isResponse;
        this.candidateID = candidateID;
        this.voteCount = voteCount;
    }

    public void setInquiry(boolean inquiry) {
        isInquiry = inquiry;
    }

    public void setResponse(boolean response) {
        isResponse = response;
    }

    public boolean isInquiry() {
        return isInquiry;
    }

    public boolean isResponse() {
        return isResponse;
    }

    public void setCandidateID(int candidateID) throws IllegalArgumentException {
        if (candidateID < 0 || candidateID > MAX_CANDIDATE_ID) {
            throw new IllegalArgumentException("Bad Candidate ID: " + candidateID);
        }
        this.candidateID = candidateID;
    }

    public int getCandidateID() {
        return candidateID;
    }

    public void setVoteCount(long count) {
        if ((count != 0 && !isResponse) || count < 0) {
            throw new IllegalArgumentException("Bad vote count");
        }
        voteCount = count;
    }

    public long getVoteCount() {
        return voteCount;
    }

    @Override
    public String toString() {
        String res = (isInquiry ? "inquiry" : "vote") + " for candidate " + candidateID;
        if (isResponse) {
            res = "response to " + res + " who now has " + voteCount + " vote(s)";
        }
        return res;
    }
}
